package com.km.wskj.itmonitor.pager.monitor.quota;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.SpannableString;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.TypeStatistics;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.utils.FloatUtils;
import com.zxl.zxlapplibrary.http.callback.StringCallback;
import com.zxl.zxlapplibrary.util.LogUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @author by Xianling.Zhou on 2017/5/9.
 */
//运维指标页面
public class QuotaActivity extends LActivity {
    private static final String TAG = "QuotaActivity";
    @BindView(R.id.tool_bar_back)
    ImageView toolBarBack;
    @BindView(R.id.tool_bar_title)
    TextView toolBarTitle;
    @BindView(R.id.alarm_distribution_pieChart)
    PieChart alarmDistributionPieChart;
    @BindView(R.id.alarm_handle_pieChart)
    PieChart alarmHandlePieChart;
    @BindView(R.id.server_pieChart)
    PieChart serverPieChart;
    @BindView(R.id.db_pieChart)
    PieChart dbPieChart;
    @BindView(R.id.net_pieChart)
    PieChart netPieChart;


    private ArrayList<PieEntry> entries;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quota);
        ButterKnife.bind(this);
        toolBarTitle.setText("运维指标");
        toolBarBack.setVisibility(View.VISIBLE);
        initData();
    }

    private void initData() {
        initAlarmChart();
        initServerChart();
        initDbChart();
        initNetChart();
    }

    //初始化网络统计
    private void initNetChart() {
        //类型统计
        pdc.netTypeStatis(HTTP_TASK_TAG, new ZxlGenericsCallback<List<TypeStatistics>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
            }

            @Override
            public void onResponse(List<TypeStatistics> typeStatistics, int i) {
                entries = new ArrayList<>();
                int total = 0;

                for (TypeStatistics tys : typeStatistics
                        ) {
                    //添加数据
                    entries.add(new PieEntry(Float.parseFloat(tys.num + ""), tys.typeName + ""));
                    total += tys.num;
                }

                initChart(netPieChart, entries, "", "网络总数\n" + total);

            }
        });
    }

    //初始化数据库统计
    private void initDbChart() {
//类型统计
        pdc.dbTypeStatis(HTTP_TASK_TAG, new ZxlGenericsCallback<List<TypeStatistics>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
            }

            @Override
            public void onResponse(List<TypeStatistics> typeStatistics, int i) {
                entries = new ArrayList<>();
                int total = 0;

                for (TypeStatistics tys : typeStatistics
                        ) {
                    //添加数据
                    entries.add(new PieEntry(Float.parseFloat(tys.num + ""), tys.typeName + ""));
                    total += tys.num;
                }

                initChart(dbPieChart, entries, "", "数据库总数\n" + total);
            }
        });
    }

    //初始化服务器统计
    private void initServerChart() {
        //服务器类型统计
        pdc.serverTypeStatis(HTTP_TASK_TAG, new ZxlGenericsCallback<List<TypeStatistics>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
            }

            @Override
            public void onResponse(List<TypeStatistics> typeStatistics, int i) {
                entries = new ArrayList<>();
                int total = 0;

                for (TypeStatistics tys : typeStatistics
                        ) {
                    //添加数据
                    entries.add(new PieEntry(Float.parseFloat(tys.num + ""), tys.typeName + ""));
                    total += tys.num;
                }

                initChart(serverPieChart, entries, "服务器分布图", "服务器总数\n" + total);

            }
        });
    }

    //初始化报警统计
    private void initAlarmChart() {
        //类型统计
        pdc.typeCount(HTTP_TASK_TAG, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                showErrorTip("加载失败");
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(String s, int i) {
                entries = new ArrayList<>();
                JSONObject jsonObject = JSON.parseObject(s);
                JSONArray jsonArray = jsonObject.getJSONArray("DATA");
                int total = 0;

                for (int j = 0; j < jsonArray.size(); j++) {
                    JSONArray arr = (JSONArray) jsonArray.get(j);
                    //添加数据
                    entries.add(new PieEntry(Float.parseFloat(arr.get(0) + ""), arr.get(1) + ""));
                    total += (int) arr.get(0);
                }
                initChart(alarmDistributionPieChart, entries, "报警分布图", "总报警数\n" + total);
            }
        });
        //状态统计
        pdc.statusCount(HTTP_TASK_TAG, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                showErrorTip("加载失败");
                LogUtils.e("error", e);
            }

            @Override
            public void onResponse(String s, int i) {
                entries = new ArrayList<>();
                JSONObject jsonObject = JSON.parseObject(s);
                JSONArray jsonArray = jsonObject.getJSONArray("DATA");
                float total = 0;
                float handle = 0;
                for (int j = 0; j < jsonArray.size(); j++) {
                    JSONArray arr = (JSONArray) jsonArray.get(j);
                    //添加数据
                    String str = "未处理";
                    if (arr.get(1).toString().equals("1")) {
                        str = "已处理";
                        handle += (int) arr.get(0);
                    }

                    entries.add(new PieEntry(Float.parseFloat(arr.get(0) + ""), str));
                    total += (int) arr.get(0);
                }
                //百分比
                float f = (handle / total) * 100;
                initChart(alarmHandlePieChart, entries, "报警处理率"
                        , "报警处理率\n" + FloatUtils.doubleFloat(f) + "%");
            }
        });

    }

    /**
     * @param mPieChart 控件
     * @param entries   数据
     * @param str       比例图名称
     * @param centerStr 饼图中心标题
     */
    private void initChart(PieChart mPieChart, ArrayList<PieEntry> entries, String str, String centerStr) {
        //设置饼图是否使用百分比
        mPieChart.setUsePercentValues(true);
        //设置饼图右下角的文字描述
      /*  Description d = new Description();
        d.setText(str);
        mPieChart.setDescription(d);*/
        mPieChart.getDescription().setEnabled(false);
        mPieChart.setExtraOffsets(5, 10, 5, 5);

        mPieChart.setDragDecelerationFrictionCoef(0.95f);
        //设置中间文件
        mPieChart.setCenterText(generateCenterSpannableText(centerStr));

        mPieChart.setDrawHoleEnabled(true);
        mPieChart.setHoleColor(Color.WHITE);

        mPieChart.setTransparentCircleColor(Color.WHITE);
        mPieChart.setTransparentCircleAlpha(110);

        mPieChart.setHoleRadius(58f); //设置中间圆盘的半径,值为所占饼图的百分比
        mPieChart.setTransparentCircleRadius(61f);//设置中间透明圈的半径,值为所占饼图的百分比
        mPieChart.setDrawCenterText(true);


        mPieChart.setRotationAngle(0);
        // 触摸旋转
        mPieChart.setRotationEnabled(true);
        mPieChart.setHighlightPerTapEnabled(true);

        //变化监听
//        mPieChart.setOnChartValueSelectedListener(this);

        //设置数据
        setData(entries, mPieChart, str);

        mPieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);

        //设置比例图
        Legend l = mPieChart.getLegend();
        l.setEnabled(false);
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.CENTER);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);
        l.setXEntrySpace(7f);//设置距离饼图的距离，防止与饼图重合
        l.setYEntrySpace(0f);
        l.setYOffset(0f);
        l.setForm(Legend.LegendForm.SQUARE);//设置比例块形状，默认为方块
        //        l.setEnabled(false);//设置禁用比例块
        //设置比例块换行...
//        l.setWordWrapEnabled(true);


        // 输入标签样式
        mPieChart.setEntryLabelColor(Color.WHITE);
        mPieChart.setEntryLabelTextSize(12f);
    }

    @OnClick(R.id.tool_bar_back)
    public void back() {
        finish();
    }


    //设置中间文字
    private SpannableString generateCenterSpannableText(String str) {
        //原文：MPAndroidChart\ndeveloped by Philipp Jahoda
        SpannableString s = new SpannableString(str);
        //s.setSpan(new RelativeSizeSpan(1.7f), 0, 14, 0);
        //s.setSpan(new StyleSpan(Typeface.NORMAL), 14, s.length() - 15, 0);
        // s.setSpan(new ForegroundColorSpan(Color.GRAY), 14, s.length() - 15, 0);
        //s.setSpan(new RelativeSizeSpan(.8f), 14, s.length() - 15, 0);
        // s.setSpan(new StyleSpan(Typeface.ITALIC), s.length() - 14, s.length(), 0);
        // s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), s.length() - 14, s.length(), 0);
        return s;
    }

    //设置数据
    private void setData(ArrayList<PieEntry> entries, PieChart mPieChart, String str) {

        PieDataSet dataSet = new PieDataSet(entries, str);
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);

        //数据和颜色
        ArrayList<Integer> colors = new ArrayList<>();

        /*for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());*/

        int[] MyColors = {
                Color.rgb(0, 238, 118), Color.rgb(100, 149, 237),
                Color.rgb(0, 191, 255), Color.rgb(255, 165, 0)
        };

        for (int c : MyColors)
            colors.add(c);


        dataSet.setColors(colors);
        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.WHITE);
        mPieChart.setData(data);
        mPieChart.highlightValues(null);

        //刷新
        mPieChart.invalidate();
    }


    @OnClick(R.id.tool_bar_back)
    public void onViewClicked() {
        finish();
    }
}
